import { createStore } from 'vuex'
import defaultConf from './defaultConf'

interface stateTypeConfig {
  defaultRoutes: Array<object>
  dynamicRoutes: Array<object>
  menuList: Array<object>
  breadcrumb: Array<object>
  confAll: object
}


const store = createStore({
  state () {
    return {
      defaultRoutes: [],
      dynamicRoutes: [],
      menuList: [],
      breadcrumb: [],
      confAll: defaultConf
    }
  },
  mutations: {
    setDefaultRoutes (state: stateTypeConfig, data: Array<object>) {
      state.defaultRoutes = data
    },
    setMenuList (state: stateTypeConfig, data: Array<object>) {
      state.menuList = data
    },
    setDynamicRoutes (state: stateTypeConfig, data: Array<object>) {
      state.dynamicRoutes = data
    },
    setBreadcrumb (state: stateTypeConfig, data: Array<object>) {
      state.breadcrumb = data
    },
    setConfig (state: stateTypeConfig, data: object) {
      state.confAll = Object.assign({}, state.confAll, data)
    }
  },
  actions: {
    setMenuList ({ state, commit }: any) {
      let menu: Array<Object> = []
      state.dynamicRoutes.forEach((level1: any) => {
        const { children, meta = {} } = level1
        if (meta.unShowChild) {
          children.forEach((level2: any) => {
            !level2.hidden && menu.push(level2)
          })
        } else {
          menu.push(level1)
        }
      })
      commit('setMenuList', menu)
    },
    setDynamicRoutes ({ state, commit }: any) {
      let newRoutes: Array<object> = []
      const userType: number = Number(localStorage.getItem('userType'))
      state.defaultRoutes.forEach((item: any) => {
        const { children, title, meta: { showTypeList, unShowChild } } = item
        let level1Bread = { title }
        if (showTypeList.includes(userType)) {
          children.forEach((level2: any) => {
            const { title, path, children = [], meta } = level2
            level2.meta = meta || {}
            level2.meta.title = title
            let level2Bread = { title, path }
            level2.meta.breadcrumb = unShowChild ? [level2Bread] : [level1Bread, level2Bread]
            if (children.length) {
              children.forEach((level3: any) => {
                const { title, path, meta } = level3
                level3.meta = meta || {}
                level3.meta.title = title
                let level3Bread = { title, path }
                level3.meta.breadcrumb = unShowChild ? [level2Bread, level3Bread] : [level1Bread, level2Bread, level3Bread]
                item.children.push({...level3, hidden: true})
              })
              delete level2.children
            }
          })
          newRoutes.push(item)
        }
      })
      commit('setDynamicRoutes', newRoutes)
      return newRoutes
    }
  },
  modules: {
  }
})
export default store
